import Taro from '@tarojs/taro'
import { concatUrl, isFunction } from '@/utils'

const app = Taro.getApp()
const pages = app.config.pages

// 命令与路径对照表
const linkMap = {
    // 商品列表
    'goodsList': 'pages/goods/list/index',
    // 商品详情
    'goods': 'pages/goods/details/index',
    // 年卡
    'annual': 'pages/annual/index/index',
    // 我的车库
    'car': 'pages/car/list/index',
    // 卡券列表
    'coupon': 'pages/coupon/index/index',
    // 车辆检测
    'detection': 'pages/detection/record/index',
    // 门店列表
    'store': 'pages/store/index/index',
    // 首页
    'index': 'pages/tabbar/index/index',
    // 购物车
    'cart': 'pages/tabbar/cart/index',
    // 分类
    'category': 'pages/tabbar/category/index',
    // 我的(个人中心)
    'user': 'pages/tabbar/user/index',
    // 保养助手
    'maintain': 'pages/maintain/list/index',
    // 专题
    'topic': 'pages/webview/h5/index',
    // 直播
    'live': 'pages/live/index/index',
    // 年卡订单确认
    'annual-order': 'pages/order/index/index',
}

interface CommandCb {
    (string): void
}

type NavigateToCb = CommandCb | null | undefined

// 判断是否属于TabBar
const isTabBar = (link: string): boolean => pages.includes(link)

export const changeToLink = (command: ICommand) => {
    if (!command) return ''
    if (!command.commandName) return ''
    let route = '/' + linkMap[command.commandName]
    const tabBar = isTabBar(linkMap[command.commandName])
    if (command.query) {
        route = concatUrl(route, command.query)
    }
    return {
        isTabBar: tabBar,
        url: route
    }
}

export default function(command: ICommand, cb?: NavigateToCb) {
    const link = changeToLink(command)
    if (link) {
        if (cb && isFunction(cb)) {
            return cb(link)
        }
        if (link.isTabBar) {
            Taro.switchTab({ url: link.url })
        } else {
            Taro.navigateTo({ url: link.url })
        }
    } else {
        return link
    }
}
